package com.qf.mvc2203.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductInterceptor implements HandlerInterceptor {
    /*
     * 注意：返回值为true，代表当前请求可以继续向后发送给Controller的handler方法
     *
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("start", System.currentTimeMillis());
        System.out.println("pre---");
        //判断当前请求是否登录过
        String token = request.getHeader("token");
        if (token != null && !token.equals("")) {
            return true;//放行当前请求，会让请求继续交给后面的handler处理
        } else {
            //用户没登陆过，重定向到登录页
            response.sendRedirect("/form.html");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long end = System.currentTimeMillis();
        long start = (long) request.getAttribute("start");
        System.out.println("时间:" + (end - start));
        System.out.println("post---");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after---");
    }
}
